package com.supor.aiot.common.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseNfcActivity;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.helper.NFCHelper;
import com.supor.aiot.common.utils.NFCCheckUtils;
import com.supor.nfc.lib.common.BuildHelper;
import com.supor.nfc.lib.utils.HexUtil;
import com.supor.nfc.lib.utils.NfcUtils;

import java.lang.ref.WeakReference;
import java.util.Arrays;

import pl.droidsonroids.gif.GifImageView;

/**
 * @author Xiaozhuang
 * @date 2021/11/15
 * @description 拉起NFC弹窗发数据
 */
public class NFCDeviceActivity extends BaseNfcActivity {

    PopupWindow popupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;

    private float alpha;
    int duration = 500;
    int sleepTime = duration / 100;
    ImageView ivFinish;
    TextView tvDialogText;
    TextView tvDialogTip;
    TextView tvDialogTip1;
    Button popCancel;
    GifImageView gifIv;

    private AppBasicDialog failureDialog;
    private String writeData = null;
    private String productId = null;
    private boolean failureDialogHide = true; //错误提示弹窗是否隐藏
    private String grindingCup = "";

    public void initNFCPop(Activity activity) {
        activityReference = new WeakReference<>(activity);
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    findViewById(R.id.vw_pop_bg).setAlpha((Float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_nfc, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.popup_window_anim);

        ivFinish = view.findViewById(R.id.iv_finish);
        gifIv = view.findViewById(R.id.gif_iv);
        tvDialogText = view.findViewById(R.id.tv_dialog_text);
        tvDialogTip = view.findViewById(R.id.tv_dialog_tip);
        tvDialogTip1 = view.findViewById(R.id.tv_dialog_tip1);
        tvDialogTip1.setVisibility(View.GONE);
        popCancel = view.findViewById(R.id.pop_cancel);

        popCancel.setOnClickListener(v -> {
            popupWindow.dismiss();
            SuporPresenter.getInstance().reportNFCWriteStatus(0);
        });
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(() -> ThreadUtils.execute(() -> {
            while (alpha > 0f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha -= 0.01f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }

            // 错误弹窗
            if (failureDialogHide) {
                finish();
            }
        }));
    }

    public void showNFCPop(Activity activity, View rootView) {
        ivFinish.setVisibility(View.GONE);
        switch (writeData.charAt(1)) {
            case '1':
                tvDialogText.setVisibility(View.VISIBLE);
                tvDialogTip.setText(R.string.nfc_write_tips);
                tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.sp_16));
                tvDialogTip.setTextColor(activity.getResources().getColor(R.color.content_default));
                tvDialogTip1.setVisibility(View.VISIBLE);
                tvDialogTip1.setText(R.string.nfc_dialog_tip);
                break;
            case '2':
                tvDialogText.setVisibility(View.VISIBLE);
                tvDialogTip.setText(R.string.nfc_write_tips2);
                tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.sp_16));
                tvDialogTip.setTextColor(activity.getResources().getColor(R.color.content_default));
                tvDialogTip1.setVisibility(View.VISIBLE);
                tvDialogTip1.setText(R.string.nfc_dialog_tip);
                // 02000000000002表示删除智定义
                if (writeData.charAt(2) == '0' && writeData.charAt(3) == '0') {
                    tvDialogText.setVisibility(View.VISIBLE);
                    tvDialogTip.setText(R.string.nfc_write_tips3);
                    tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.sp_16));
                    tvDialogTip.setTextColor(activity.getResources().getColor(R.color.content_default));
                    tvDialogTip1.setVisibility(View.VISIBLE);
                    tvDialogTip1.setText(R.string.nfc_dialog_tip);
                }
                break;
            case '0':
                if (writeData.charAt(2) == '0') {
                    tvDialogText.setVisibility(View.VISIBLE);
                    tvDialogTip.setText("碰一碰，添加干磨杯配件");
                    tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.sp_16));
                    tvDialogTip.setTextColor(activity.getResources().getColor(R.color.content_default));
                    tvDialogTip1.setVisibility(View.VISIBLE);
                    tvDialogTip1.setText("请靠近标签，停留3秒后移开手机");
                }
                break;
            default:
                break;
        }

        ivFinish.setVisibility(View.INVISIBLE);
        gifIv.setVisibility(View.VISIBLE);
        popCancel.setVisibility(View.VISIBLE);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        alpha = 0f;
        ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.01f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isNFCPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void touchSuccess() {
        String tip = getString(R.string.nfc_success_tips);
        if (writeData.charAt(1) == '2') {
            tip = getString(R.string.nfc_write_success);
            // 02000000000002表示删除智定义
            if (writeData.charAt(2) == '0' && writeData.charAt(3) == '0') {
                tip = getString(R.string.nfc_write_success2);
            }
        } else if (writeData.charAt(1) == '0') {
            if (writeData.charAt(2) == '0') {
                tip = "干磨杯配件添加成功";
//                tvDialogText.setVisibility(View.VISIBLE);
//                tvDialogTip.setText("碰一碰，添加干磨杯配件");
//                tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.sp_16));
//                tvDialogTip.setTextColor(getResources().getColor(R.color.content_default));
//                tvDialogTip1.setVisibility(View.VISIBLE);
//                tvDialogTip1.setText("请靠近标签，停留3秒后移开手机");
            }
        }
        touchSuccess(tip);
    }

    public void touchSuccess(String tips) {
        ivFinish.setVisibility(View.VISIBLE);
        tvDialogText.setVisibility(View.INVISIBLE);
        if (!TextUtils.isEmpty(tips)) {
            tvDialogTip.setText(tips);
        }
        tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activityReference.get().getResources().getDimensionPixelSize(R.dimen.sp_16));
        tvDialogTip.setTextColor(activityReference.get().getResources().getColor(R.color.content_default));
        gifIv.setVisibility(View.INVISIBLE);
        tvDialogTip1.setVisibility(View.VISIBLE);
        tvDialogTip1.setText(R.string.nfc_operate_success2);
        popCancel.setVisibility(View.INVISIBLE);
        handler.postDelayed(this::dismissNFCPop, 2500);
    }

    public void dismissNFCPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    @Override
    protected int resourceId() {
        return 0;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_device);
    }

    @Override
    public void initData() {
        super.initData();
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            writeData = bundle.getString(Constants.Key.DATA);
            productId = bundle.getString(Constants.Key.PRODUCT_ID);
            grindingCup = bundle.getString(Constants.Key.GRINDING_CUP);
        }
        initNFCPop(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (NfcUtils.NFC_STATE == 1 && failureDialogHide) {
            showErrorDialog("该机型不支持NFC功能");
            return;
        }
        if (hasFocus && failureDialogHide) showNFCPop(this, findViewById(R.id.ll_root));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!isNFCPopShow()) {
            return;
        }
        if (NfcUtils.mNfcAdapter == null) {
            NfcUtils.init(this);
            NfcUtils.configNfc(this);
        }
        // 在onNewIntent中处理由NFC设备传递过来的intent
        process(intent);
    }

    private void process(Intent intent) {
        RecordBean recordBean = NFCHelper.getInstance().processIntent(intent);
        if (recordBean == null) {
//            showNFCFailureDialog();
            // 增加合法性校验
            String pkg = NFCHelper.getInstance().checkPKG(intent);
            int status = NFCCheckUtils.STATUS_ILLEGAL;
            switch (pkg) {
                case "com.midea.ai.appliances":
                    status = NFCCheckUtils.STATUS_ILLEGAL_MEDIA;
                    break;
                case "com.haier.uhome.uplus":
                    status = NFCCheckUtils.STATUS_ILLEGAL_HAIER;
                    break;
                case "com.joyoung.joyoungsmart":
                    status = NFCCheckUtils.STATUS_ILLEGAL_JOYA;
                    break;
                case "com.xiaomi.smarthome":
                    status = NFCCheckUtils.STATUS_ILLEGAL_XIAOMI;
                    break;
                default:
                    break;
            }
            checkNFC(status);
            return;
        }

        // WiFi类NFC模块存在没有pid的情况
        if (TextUtils.isEmpty(recordBean.getProductId())) {
            showDialog("提示","设备选择错误\n请选择正确的设备");
            return;
        }

        // Pid是否已接入Saas后台
        if (!NFCCheckUtils.checkPidAccess(recordBean.getProductId())) {
            dismissNFCPop();
            new Handler().postDelayed(() -> {
                NFCCheckUtils.startResultActivity(this, NFCCheckUtils.STATUS_NO_EXIT, false);
            }, 500);
        } else {
            // 判断碰一碰设备类型是否匹配
            if (!recordBean.getProductId().equalsIgnoreCase(productId)) {
                if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)) {
                    showErrorDialog(String.format(getString(R.string.device_productId_check), "免手洗破壁机(Q8)"));
                } else if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
                    showErrorDialog(String.format(getString(R.string.device_productId_check), "电炖锅(DG35YC18)"));
                } else {
                    showDialog("提示","设备选择错误\n请选择正确的设备");
                }
                return;
            }
        }

        if (!TextUtils.isEmpty(grindingCup)) {
            SuporPresenter.getInstance().reportCupCondition(recordBean.getcValue());
            touchSuccess();
            return;
        }

        // 头四个字节 + F4
        byte[] head = NFCHelper.getInstance().readNfcA(intent, 0x60, 0x61);
        Logc.e("head: " + Arrays.toString(head));
        if (head == null) {
//            ToastUtils.getInstance().showCustomToast("读取头信息失败");
            showNFCFailureDialog();
            return;
        }

        // F4 产品当前正常烹饪的菜谱ID
        String F4 = HexUtil.encodeHexStr(new byte[]{head[4], head[5]});
        Logc.e("F4 :" + F4);
//        if ((head[5] & 0xFF) != 0) {
//            ToastUtils.getInstance().showCustomToast("当前正常烹饪的菜谱ID: " + F4);
//        }

        // 下发指令优化
        // 1、先判断F1标志
        if ((head[1] & 0xFF) == 1) {
            if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)) {
//                showErrorDialog(String.format(getString(R.string.device_power_check), "免手洗破壁机(Q8)"));
                showErrorDialog("请确认是否接通电源或正确安放搅拌杯");
            } else if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
                showErrorDialog(String.format(getString(R.string.device_power_check), "电炖锅(DG40YC18)"));
            }
            return;
        }
        // 2、再判断F2
        if ((head[2] & 0xFF) != 1) {
//            String msg = String.format(getString(R.string.device_power_check), "免手洗破壁机(Q8)");
            String msg = "请确认是否接通电源或正确安放搅拌杯";
            if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
                msg = String.format(getString(R.string.device_power_check), "电炖锅(DG40YC18)");
            }
            if ((head[2] & 0xFF) == 2) {
                msg = String.format(getString(R.string.device_working_check), "免手洗破壁机(Q8)");
                if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
                    msg = String.format(getString(R.string.device_working_check), "电炖锅(DG40YC18)");
                }
            } else if ((head[2] & 0xFF) == 3) {
                msg = recordBean.getError();
            }
            showErrorDialog(msg);
            Logc.e("head: " + (head[0] & 0xFF) + ", " + (head[1] & 0xFF) + ", "
                    + (head[2] & 0xFF) + ", " + (head[3] & 0xFF));
            return;
        }

        // 3、 最后判断F5
        if ((head[6] & 0xFF) == 2) {
            // 空杯提示
            showErrorDialog("请确认是否接通电源或正确安放搅拌杯");
            return;
        }


       // APP写入
        head[1] = 1;

        byte[] data = null;
        //设备不匹配无法写入
        if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)
                || Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
            data = BuildHelper.buildDataForBlender(head, HexUtil.decodeHex(writeData));
        }
        Logc.d("write: data: " + (HexUtil.encodeHexStr(data)));
        //设备不匹配提示
        if (data == null) {
//            showErrorDialog("设备不匹配");
            return;
        }

        // 在写入指令之前，判断是否需要更新虚拟UID
        DeviceInfo vrDevice = NFCCheckUtils.getVirtualDeviceByPid(recordBean.getProductId());
        if (vrDevice != null) {
            // 更新mac
            SuporPresenter.getInstance().updateMac(recordBean.getSn(), vrDevice.mac);
        }

        boolean success = NFCHelper.getInstance().writeNfcA(intent, data);
        if (success) {
            // 杯体判断是否正确
            if ((head[6] & 0xFF) != getCupType()) {
                SuporPresenter.getInstance().reportNFCWriteStatus(0);
                showErrorDialog("当前使用的刀座与食谱不符，请替换为湿磨刀座/干磨刀座");
                return;
            }
            SuporPresenter.getInstance().reportNFCWriteStatus(1);
            touchSuccess();
        } else {
            Logc.e(TAG, "nfca write failed");
            showNFCFailureDialog();
        }
    }

    private void checkNFC(int status) {
        dismissNFCPop();
        handler.postDelayed(
                () -> NFCCheckUtils.startResultActivity(this, status, true), 700);
    }

    private void showNFCFailureDialog() {
        showDialog(getString(R.string.nfc_touch_failure), getString(R.string.nfc_touch_failure_tip));
    }

    private void showErrorDialog(String error) {
        String title = "提示";
        String errorText = error;
        // 破壁机Q8错误提示
        if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)) {
            title = "E" + error + "故障";
            switch (error) {
                case "4":
                    errorText = "出浆阀出现堵塞";
                    break;
                case "5":
                    errorText = "水箱水位为空：请将纯净水添加至水箱， 并添加至所需水位线（需超过最低水位线）";
                    break;
                case "6":
                    errorText = "熬煮杯未放到位：请将熬煮杯放置托盘相应位置";
                    break;
                case "7":
                    errorText = "出浆嘴未放到位：请先将搅拌杯取出，并将出浆嘴放置相应位置，再还搅拌杯";
                    break;
                case "A":
                case "B":
                case "C":
                case "D":
                    errorText = "E10故障中";
                    break;

                default:
                    title = "提示";
                    break;
            }
        } else if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
            title = "E" + error + "故障";
            switch (error) {
                case "1":
                    title = "E0故障";
                    errorText = "顶部传感器故障，请联系4008899717客服";
                    break;

                default:
                    title = "提示";
                    break;
            }
        }

        showDialog(title, errorText);
    }

    private void showDialog(String title, String message) {
        dismissNFCPop();
        if (failureDialog != null) {
            if (failureDialog.isShowing()) {
                return;
            } else {
                failureDialog.show();
            }
            return;
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.dialog_ack, (dialog, which) -> {
            dialog.cancel();
            SuporPresenter.getInstance().reportNFCWriteStatus(0);
            handler.postDelayed(this::finish, 500);
        });
        failureDialog = builder.create();
        failureDialog.setCancelable(false);
        failureDialog.show();
        failureDialogHide = false;
    }

    private int getCupType() {
        int ct = 0;
        if (writeData != null) {
            String sts = writeData.substring(2, 4);
            int st = Integer.parseInt(sts, 16);
            if (st > 10 && st < 21) ct = 1;
        }
        return ct;
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return false;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}